package com.wonders.hisdoctor.station.util;

import com.wonders.his.common.utils.DateUtils;
import com.wonders.his.framework.service.RedisCacheService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Description: 处方明细Id生成器
 *
 * @author tongaijie
 * <p>
 * Create: 2021-01-28 15:35
 */
@Component
public class PrecsIdGenerator {

    private final RedisCacheService redisCache;

    /**
     * 令牌有效期（默认24小时）
     */
    @Value("${token.expireTime}")
    private int expireTime;

    public PrecsIdGenerator(RedisCacheService redisCache) {
        this.redisCache = redisCache;
    }

    public String getPrescId(){
        String dateStr = DateUtils.parseDateToStr(DateUtils.YYYYMMDD,new Date());
        // 首先判断redis中是否存在当前日期的key
        if(redisCache.getCacheObject(dateStr) != null){
            // 存在，则更新value，设置为++
            Long cache = redisCache.getCacheObject(dateStr);
            Long value = cache + 1;
            redisCache.setCacheObject(dateStr, value, expireTime, TimeUnit.HOURS);
            return String.valueOf(value);
        } else {
            // 如果不存在
            // 添加key value
            String value = dateStr+"00001";
            Long valueLong = Long.valueOf(value);
            redisCache.setCacheObject(dateStr,valueLong, expireTime, TimeUnit.HOURS);
            return value;
        }
    }

}
